const db = require("../../database");
// 引入jsonwebtoken
const jwt = require("jsonwebtoken");
const { secretKey } = require("../../config");
exports.login = (req, res) => {
    const { username, password } = req.body || {};
    // 查询用户是否存在
    const sql = `select * from users where username = ?`;
    db.query(sql, [username], (err, results) => {
        if (err)
            return res.send({
                success: false,
                status: 0,
                msg: err.message,
            });
        if (!results.length) {
            return res.send({
                success: true,
                status: 0,
                msg: "用户不存在",
            });
        }
        const passwordServer = (results || [])[0].password;
        console.log("password=", password);
        console.log("passwordServer=", passwordServer);
        if (passwordServer !== password) {
            return res.send({
                success: true,
                status: 0,
                msg: "密码不匹配",
            });
        }
        // 登录成功，通过jwt加密用户信息
        const token = jwt.sign(
            {
                data: {
                    username: results[0].username,
                    id: results[0].id,
                },
            },
            secretKey,
            { expiresIn: "1h" }
        );
        res.send({
            success: true,
            status: 1,
            msg: "登录成功",
            data: token,
        });
    });
};

exports.register = (req, res) => {
    const { username, password } = req.body || {};
    // 查询用户是否存在
    const sql = `select * from users where username = ?`;
    db.query(sql, [username], (err, results) => {
        if (err) {
            return res.send({
                success: false,
                status: 0,
                msg: err.message,
            });
        }

        // 如果用户不存在就注册 存在就提示用户存在
        if (results.length) {
            return res.send({
                success: false,
                status: 0,
                msg: "用户名已存在, 请更换",
            });
        }

        // 注册用户
        const sql = `insert into users set ?`;
        db.query(sql, req.body, (err, results) => {
            if (err) {
                return res.send({
                    success: false,
                    status: 0,
                    msg: err.message,
                });
            }
            if (results.affectedRows !== 1) {
                return res.send({
                    success: false,
                    status: 0,
                    msg: "注册用户失败",
                });
            }
            res.send({
                success: true,
                status: 1,
                msg: "注册成功",
            });
        });
    });
};
